<template>
	<view class="px-2 py-4">
		<form-component :formFields="formFields" :formData="formData" :formRules="formRules" :fileLists="fileLists"
			:startUserSelectTasks="startUserSelectTasks" :startUserSelectAssignees="startUserSelectAssignees"
			:startUserSelectAssigneesFormRules="startUserSelectAssigneesFormRules" :detailId="detailId"
			:resubmit="resubmit" @submitForm="submitForm" @cancelForm="cancelForm" />
	</view>
</template>

<script setup lang="ts">
import {
	onLoad
} from "@dcloudio/uni-app";
import { ref, reactive, nextTick, computed } from 'vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { buildFileList } from '@/utils/fileUtils'
import { getAccessToken } from '@/utils/auth'
import * as DefinitionApi from '@/api/bpm/definition'
import * as Meeting from '@/api/oa/meeting'
import * as UserApi from '@/api/system/user/index'
import { useMessage, useToast } from 'wot-design-uni'
import { formatDate, parseDateToTimestamp } from '@/utils/formatTime'


const message = useMessage()
const toast = useToast()
const globalConfig = (getApp() as any).globalData.config;
const detailId = ref(null)
const userList = ref<any[]>([])
const resubmit = ref(0)


const headerObj = ref(
	{
		Authorization: 'Bearer ' + getAccessToken()
	}
)

// 指定审批人
const processDefineKey = 'metting' // 流程定义 Key
const startUserSelectTasks = ref<any>([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref<any>({}) // 发起人选择审批人的数据
const startUserSelectAssigneesFormRef = ref() // 发起人选择审批人的表单 Ref
const startUserSelectAssigneesFormRules = ref<any>({}) // 发起人选择审批人的表单 Rules
const depList = ref<any[]>([]) // 部门列表
const meetingRoomList = ref<any[]>([])
const userProfile = ref<any>({})

// 独立文件存储（按字段名存储）
const fileLists = ref<Record<string, any[]>>({
	deskTagAttachments: []
})

const handleMeetingRoomChange = ({ value }: { value: any }) => {
	console.log('value', value);
	// 查找选中的会议室
	const selectedRoom = meetingRoomList.value.find(room => room.id === value);
	console.log('selectedRoom', selectedRoom);
	if (selectedRoom && selectedRoom.managerIds) {
		// 如果有startUserSelectTasks并且存在管理员ID
		if (startUserSelectTasks.value?.length > 0) {
			// 将managerIds转为数组(如果是字符串)
			let managerIds = selectedRoom.managerIds;
			if (typeof managerIds === 'string') {
				managerIds = managerIds.split(',').map(Number);
			} else if (!Array.isArray(managerIds)) {
				managerIds = [managerIds]; // 如果是单个数字
			}
			console.log('managerIds', managerIds);
			console.log('startUserSelectTasks', startUserSelectTasks.value);
			console.log('startUserSelectAssignees', startUserSelectAssignees.value);
			// 为每个任务设置审批人
			for (const userTask of startUserSelectTasks.value) {
				startUserSelectAssignees.value[userTask.id] = managerIds;
			}
		}
	}
}

//表单项字段配置
const formFields = ref<any[]>([
	{
		type: 'select',
		prop: 'mrId',
		label: '会议室选择',
		placeholder: '会议室',
		filterable: true,
		options: () => meetingRoomList.value,  // 绑定 options 列表
		labelKey: 'mrName',
		valueKey: 'id',
		onChange: handleMeetingRoomChange,
	},

	{
		type: 'radio',
		prop: 'isNeedMedia',
		label: '是否需要媒体',
		required: true,
		inline: true,
		options: [
			{ label: '是', value: 1 },
			{ label: '否', value: 0 }
		],
		optionLabel: 'label',
		optionValue: 'value',

	},
	{
		type: 'radio',
		prop: 'isPrintDeskTag',
		label: '是否需要桌签',
		required: true,
		inline: true,
		options: [
			{ label: '是', value: 1 },
			{ label: '否', value: 0 }
		],
		optionLabel: 'label',
		optionValue: 'value',

	},
	{
		type: 'upload', prop: 'deskTagAttachments', label: '桌签附件', placeholder: '请输入桌签附件',
		action: globalConfig.uploadUrl,
		limit: 1,
		visible: (formData: any) => formData.isPrintDeskTag === 1,
		accept: 'all',
		header: headerObj.value,
		targetMapping: {         // 字段映射配置
			fileUrl: 'deskTagAttachments',    // 接口返回ID -> formData.serverIds
			fileName: 'ename'     // 文件名 -> formData.fileName
		}
	},
	{
		type: 'input',
		prop: 'meetName',
		label: '会议名称',
		placeholder: '请输入名称'
	},
	{
		type: 'textarea',
		prop: 'meetDesc',
		label: '会议描述',
		placeholder: '请输入描述',
	},
	{
		type: 'datetime',
		prop: 'beginTime',
		label: '开始时间',
		placeholder: '选择时间',
		datetimeType: 'datetime',
	},
	{
		type: 'datetime',
		prop: 'endTime',
		label: '结束时间',
		placeholder: '选择时间',
		datetimeType: 'datetime',
		get minDate() {
			return typeof formData.value.beginTime === 'number'
				? formData.value.beginTime
				: Date.now();
		},
		get maxDate() {
			return typeof formData.value.beginTime === 'number'
				? formData.value.beginTime + 24 * 60 * 60 * 1000
				: Date.now() + 24 * 60 * 60 * 1000;
		}
	}
])
const formData = ref<any>({
	isNeedMedia: 0,
	isPrintDeskTag: 0,

} as any)
const formRules = reactive({
	mrId: [{ required: true, message: '会议室不能为空', trigger: 'blur' }],
	managerId: [{ required: false, message: '审批人不能为空', trigger: 'blur' }],
	meetName: [{ required: true, message: '会议名称不能为空', trigger: 'blur' }],
	subject: [{ required: true, message: '会议主题不能为空', trigger: 'blur' }],
	beginTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
	endTime: [
		{ required: true, message: '结束时间不能为空', trigger: 'blur' },
	],
})

/** 获取用户列表 */
const getUserList = async () => {
	try {
		userList.value = await UserApi.getSimpleUserList();
	} catch (error) {
		console.error("获取用户列表失败:", error);
		userList.value = []; // 失败时，防止 userOptions.value 变成 undefined
	}
}
onLoad(async (options) => {
	const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
		undefined,
		processDefineKey
	)
	if (!processDefinitionDetail) {
		toast.error('流程模型未配置，请检查！')
		return
	}
	startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks
	console.log('startUserSelectTasks', processDefinitionDetail)
	// 设置指定审批人
	if (startUserSelectTasks.value?.length > 0) {
		// 设置校验规则
		for (const userTask of startUserSelectTasks.value) {
			startUserSelectAssignees.value[userTask.id] = []
			startUserSelectAssigneesFormRules.value[userTask.id] = [
				{

					required: true,
					message: '请选择审批人',
					validator: (value: any) => {
						console.log("当前审批人值435435:", value); // 调试输出
						if (value && Array.isArray(value) && value.length > 0) {
							console.log('value.length', value.length);
							return Promise.resolve();
						} else {
							return Promise.reject('审批人不能为空');
						}
					},
					trigger: ['change']

				}
			]
		}
		console.log('startUserSelectAssignees.value', startUserSelectAssignees.value);
		console.log('startUserSelectAssigneesFormRules.value', startUserSelectAssigneesFormRules.value);
	}
	detailId.value = options?.id
	resubmit.value = options?.resubmit
	/** 获得详情 */
	if (detailId.value) { getDetailById() }
	//加载会议室列表
	getMeetingRoomList()
	//获取用户列表
	await getUserList()


})




/** 获取页面详情 */
const getDetailById = async () => {
	try {
		const data = await Meeting.getMeeting(Number(detailId.value))
		formData.value = data
		if (formData.value.beginTime) {
			formData.value.beginTime = parseDateToTimestamp(formData.value.beginTime)
		}
		if (formData.value.endTime) {
			formData.value.endTime = parseDateToTimestamp(formData.value.endTime)
		}
		// 附件字段回显
		fileLists.value.deskTagAttachments = buildFileList(data.deskTagAttachments
		) as any;
		console.log('formData.value', formData.value);
	} catch (error) {
		console.log('加载数据失败')
	}
}

/** 获取会议列表 */
const getMeetingRoomList = async () => {
	try {
		const roomList = await Meeting.getMeetingRoomPage({ state: 1 })
		meetingRoomList.value = roomList.list
		console.log('meetingRoomList.value', meetingRoomList.value);

	} catch (error) {
		console.error("获取用户列表失败:", error);
		depList.value = []; // 失败时，防止 userOptions.value 变成 undefined
	}
}
/** 提交表单 */
const submitForm = async (payload: any) => {
	const { type, data } = payload
	if (data.beginTime) {
		data.beginTime = formatDate(data.beginTime)
	}
	if (data.endTime) {
		data.endTime = formatDate(data.endTime)
	}
	try {
		if (type === 'update') {
			await Meeting.updateMeeting(data)

			toast.success('编辑成功');



		} else {
			await Meeting.createMeeting(data)

			toast.success('新增成功');


		}


		// 成功后跳转
		// ;
	} catch (error) {
		console.error('表单提交失败:', error);
		toast.error('提交失败，请稍后再试');
	}
}

/** 取消表单 */
const cancelForm = async () => {
	try {
		// 删除的二次确认
		await message.confirm({
			msg: '您确定要取消吗？',
			title: '提示'  // 添加标题
		})
		uni.navigateTo({ url: '/pagesPackage/OAsystemAutomation/meeting/meetingrequest/index' });
		// 显示成功提示
		toast.success('取消成功')
	} catch (error) {
		console.log('用户取消了操作或发生错误:', error)
	}
}
</script>

<style scoped lang="scss">
.container {
	padding: 20px 5px;
}

.custom-shadow {
	width: 40%;
	border-radius: 5%;
}
</style>